package edu.nctu.csie.jichang.tw2cn.util;


public class Ascii2Native {
	
	private static String PREFIX = "\\u";
	/**
	 * Native to ascii string. It's same as execut native2ascii.exe.
	 * @param pValue native string
	 * @return ascii string
	 */ 
	public static String native2Ascii(String pValue) {
		char[] tChars = pValue.toCharArray();
		StringBuilder tOut = new StringBuilder();
		for (int i = 0; i < tChars.length; i++) {
			tOut.append(char2Ascii(tChars[i]));
		}
		return tOut.toString();
	}
 
	/**
	 * Native character to ascii string.
	 * @param pChar native character
	 * @return ascii string
	 */ 
	private static String char2Ascii(char pChar) {
		if (pChar > 255) {
			StringBuilder tOut = new StringBuilder();
			tOut.append(PREFIX);
			int tCode = (pChar >> 8);
			String tTemp = Integer.toHexString(tCode);
			if (tTemp.length() == 1) {
				tOut.append("0");
			}
			tOut.append(tTemp);
			tCode = (pChar & 0xFF);
			tTemp = Integer.toHexString(tCode);
			if (tTemp.length() == 1) {
				tOut.append("0");
			}
			tOut.append(tTemp);
			return tOut.toString();
		} else {
			return Character.toString(pChar);
		}
	}
 
	/**
	 * Ascii to native string. It's same as execut native2ascii.exe -reverse.
	 * @param pValue ascii string
	 * @return native string
	 */ 
	public static String ascii2Native(String pValue) {
		StringBuilder tOut = new StringBuilder();
		int tBegin = 0;
		int tIndex = pValue.indexOf(PREFIX);
		while (tIndex != -1) {
			tOut.append(pValue.substring(tBegin, tIndex));
			tOut.append(ascii2Char(pValue.substring(tIndex, tIndex + 6)));
			tBegin = tIndex + 6;
			tIndex = pValue.indexOf(PREFIX, tBegin);
		}
		tOut.append(pValue.substring(tBegin));
		return tOut.toString();
	}
	
	/**
	 * Ascii to native character.
	 * @param pValue ascii string
	 * @return native character
	 */ 
	private static char ascii2Char(String pValue) {
		if (pValue.length() != 6) {
			throw new IllegalArgumentException("Ascii string of a native character must be 6 character.");
		}
		if (!PREFIX.equals(pValue.substring(0, 2))) {
			throw new IllegalArgumentException("Ascii string of a native character must start with \"\\u\".");
		}
		String tTemp = pValue.substring(2, 4);
		int tCode = Integer.parseInt(tTemp, 16) << 8;
		tTemp = pValue.substring(4, 6);
		tCode += Integer.parseInt(tTemp, 16);
		return (char) tCode;
	}
}